﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Shop.Wares.Services;
using Shop.Wares.Models;
using System.IO;
using Shop.Core.Common;
using PetaPoco;
using Newtonsoft.Json;

namespace Shop.Wares.Controllers
{
    public class WaresController : Controller
    {
        Services.WaresAccess bll = new WaresAccess();

        #region 商品类别管理
        /// <summary>
        /// 类别管理界面
        /// </summary>
        /// <returns></returns>
        public ActionResult WaresCategory()
        {
            IList<WaresCategory> winfo = bll.GetWinfo();
            return View(winfo);
        }
        /// <summary>
        /// 添加类别时验证类别名
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult VerificationCName()
        {
            string CName = Request.Form["CName"];
            if (bll.VerificationCName(CName) == 0)
            {
                return Content("NO");
            }
            return Content("OK");
        }
        /// <summary>
        /// 修改类别时验证类别名
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UVerificationCName()
        {
            string CName = Request.Form["CName"];
            string YCName = Request.Form["YCName"];
            if (bll.UVerificationCName(CName, YCName) == 0)
            {
                return Content("NO");
            }
            return Content("OK");
        }
        /// <summary>
        /// 添加类别
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddWaresCategory()
        {
            string CName = Request.Form["CName"];
            string Describe = Request.Form["Describe"];
            WaresCategory winfo = new Models.WaresCategory();
            winfo.CName = CName;
            winfo.Describe = Describe;
            winfo.Createdate = DateTime.Now;
            winfo.OrderTime = DateTime.Now;
            bll.AddWaresCategory(winfo);
            try
            {
                return Content("OK");
            }
            catch (Exception)
            {
                return Content("NO");
            }
        }
        /// <summary>
        /// 修改类别
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UpdateWaresCategory()
        {
            int CID = Convert.ToInt32(Request.Form["CID"]);
            string CName = Request.Form["CName"];
            string Describe = Request.Form["Describe"];
            DateTime Createdate = Convert.ToDateTime(Request.Form["Createdate"]);
            WaresCategory winfo = new WaresCategory();
            winfo.CID = CID;
            winfo.CName = CName;
            winfo.Describe = Describe;
            winfo.Createdate = Createdate;
            try
            {
                bll.UpdateWaresCategory(winfo);
                return Content("OK");
            }
            catch (Exception)
            {
                return Content("NO");
            }
        }
        /// <summary>
        /// 删除类别
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DelWaresCategory()
        {
            int CID = Convert.ToInt32(Request.Form["CID"]);
            if (bll.SWCount(CID) == 0)
            {
                return Content("NO2");
            }
            if (bll.DelWaresCategory(CID) == 0)
            {
                return Content("NO");
            }
            return Content("OK");
        }
        /// <summary>
        /// 置顶类别
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult OrderTimeWaresCategory()
        {
            int CID = Convert.ToInt32(Request.Form["CID"]);
            if (bll.OrderTimeWaresCategory(CID) == 0)
            {
                return Content("NO");
            }
            return Content("OK");
        }
        #endregion
        #region 商品子类别管理
        /// <summary>
        /// 子类别管理
        /// </summary>
        /// <param name="CID"></param>
        /// <returns></returns>
        public ActionResult SonWaresCategory(int CID)
        {

            IList<SonWaresCategory> swinfo = bll.GetSWInfo(CID);
            ViewBag.CID = CID;
            return View(swinfo);
        }
        /// <summary>
        /// 添加类别时验证类别名
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult VerificationSCName()
        {
            string SCName = Request.Form["SCName"];
            if (bll.VerificationSCName(SCName) == 0)
            {
                return Content("NO");
            }
            return Content("OK");
        }
        /// <summary>
        /// 修改类别时验证类别名
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UVerificationSCName()
        {
            string SCName = Request.Form["SCName"];
            string YSCName = Request.Form["YSCName"];
            if (bll.UVerificationSCName(SCName, YSCName) == 0)
            {
                return Content("NO");
            }
            return Content("OK");
        }
        /// <summary>
        /// 添加子类别
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddSonWaresCategory()
        {
            string CName = Request.Form["SCName"];
            string Describe = Request.Form["Describe"];
            int CID = Convert.ToInt32(Request.Form["CID"]);
            SonWaresCategory swinfo = new Models.SonWaresCategory();
            swinfo.CID = CID;
            swinfo.SCName = CName;
            swinfo.Describe = Describe;
            swinfo.Createdate = DateTime.Now;
            swinfo.OrderTime = DateTime.Now;
            bll.AddSonWaresCategory(swinfo);
            try
            {

                return Content("OK");
            }
            catch (Exception)
            {
                return Content("NO");
            }

        }
        /// <summary>
        /// 修改类别
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UpdateSonWaresCategory()
        {
            int SCID = Convert.ToInt32(Request.Form["SCID"]);
            string SCName = Request.Form["SCName"];
            string Describe = Request.Form["Describe"];
            DateTime Createdate = Convert.ToDateTime(Request.Form["Createdate"]);
            SonWaresCategory swinfo = new SonWaresCategory();
            swinfo.SCID = SCID;
            swinfo.SCName = SCName;
            swinfo.Describe = Describe;
            swinfo.Createdate = Createdate;
            try
            {
                bll.UpdateSonWaresCategory(swinfo);
                return Content("OK");
            }
            catch (Exception)
            {
                return Content("NO");
            }
        }
        /// <summary>
        /// 删除子类别
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DelSonWaresCategory()
        {
            int SCID = Convert.ToInt32(Request.Form["SCID"]);
            if (bll.DelSonWaresCategory(SCID) == 0)
            {
                return Content("NO");
            }
            return Content("OK");
        }
        /// <summary>
        /// 置顶类别
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult OrderTimeSonWaresCategory()
        {
            int SCID = Convert.ToInt32(Request.Form["SCID"]);
            if (bll.OrderTimeSonWaresCategory(SCID) == 0)
            {
                return Content("NO");
            }
            return Content("OK");
        }
        #endregion

        #region 商品管理
        /// <summary>
        /// 商品管理页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Wares()
        {
            IList<WaresCategory> wcinfo = bll.GetWinfo();
            ViewBag.wcinfo = wcinfo;
            return View();
        }
        /// <summary>
        /// 添加商品页面
        /// </summary>
        /// <returns></returns>
        public ActionResult AddWares()
        {
            IList<WaresCategory> winfo = bll.GetWinfo();
            return View(winfo);
        }
        /// <summary>
        /// 添加商品
        /// </summary>
        /// <param name="FormValues"></param>
        /// <param name="Url"></param>
        /// <returns></returns>
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult AddWares(FormCollection FormValues, HttpPostedFileBase Url, HttpPostedFileBase bookLocation)
        {
            //接收在线编辑器数据
            string EditorContents = FormValues["Contents"] ?? string.Empty;
            string FullFileUrl = "";
            string FullFileBook = "";
            //接收自己单独要上传的图片            
            if (Url != null)
            {
                string RndFileName = string.Format("{0}{1}{2}", 
                    DateTime.Now.ToString("yyMMdd"), 
                    Path.GetRandomFileName().Replace(".", string.Empty),
                    Path.GetExtension(Url.FileName));
                FullFileUrl = string.Format("/upload/{0}", RndFileName);
                string SaveFilePathName = Server.MapPath(FullFileUrl);
                if (!YuHou.ReUse.ImageOperation
                    .IntelligentSaveImageFile(Url.InputStream,
                    SaveFilePathName, 0, true, "", 
                    new System.Drawing.Size(500, 500)))
                    Url.SaveAs(SaveFilePathName);
            }
            if (bookLocation != null)
            {
                string RndFileName = string
                    .Format("{0}{1}{2}", 
                    DateTime.Now.ToString("yyMMdd"), 
                    Path.GetRandomFileName().Replace(".",
                    string.Empty), Path
                    .GetExtension(bookLocation.FileName));
                FullFileBook = string.Format("/Books/{0}",
                    RndFileName);
                string SaveFilePathName = Server
                    .MapPath(FullFileBook);
                bookLocation.SaveAs(SaveFilePathName);
                EditorContents += "上传电子书成功！";
            }
            string WName = FormValues["WName"];
            int CID = Convert.ToInt32(FormValues["CID"]);
            int SCID = Convert.ToInt32(FormValues["SCID"]);
            double OPrice = Convert.ToDouble(FormValues["OPrice"]);
            double PPrice = Convert.ToDouble(FormValues["PPrice"]);
            int Stock = Convert.ToInt32(FormValues["Stock"]);
            string Describe = FormValues["Describe"];

            Models.Wares winfo = new Models.Wares();
            winfo.WName = WName;
            winfo.CID = CID;
            winfo.SCID = SCID;
            winfo.OPrice = OPrice;
            winfo.PPrice = PPrice;
            winfo.SaleNum = 0;
            winfo.Stock = Stock;
            winfo.Describe = Describe;
            winfo.Url = FullFileUrl;
            winfo.Introduce = EditorContents;
            winfo.Status = 0;
            winfo.OrderTime = DateTime.Now;
            winfo.Createdate = DateTime.Now;
            winfo.bookLocation = FullFileBook;
            try
            {
                bll.AddWares(winfo);
            }
            catch (Exception)
            {
                var scripts = ("<script>alert('添加失败');document.location.href = 'AddWares'; </script>");
                return Content(scripts);
            }
            var script = ("<script>alert('添加成功');document.location.href = 'Wares'; </script>");
            return Content(script);
        }
        /// <summary>
        /// 根据类别ID获取子类别信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Getswinfo()
        {
            int CID = Convert.ToInt32(Request.Form["CID"]);
            IList<SonWaresCategory> swinfo = bll.GetSWInfo(CID);

            return Json(swinfo, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        ///获取类别下子类别数量
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SWCount()
        {
            int CID = Convert.ToInt32(Request.Form["CID"]);
            if (bll.SWCount(CID) == 1)
            {
                return Content("NO");
            }
            return Content("OK");
        }
        /// <summary>
        /// 修改商品信息界面
        /// </summary>
        /// <returns></returns>
        public ActionResult UpdateWares(int WID)
        {
            Models.Wares winfo = bll.GetWaresInfo(WID);
            //获取要修改的商品的类别的子类别信息
            IList<SonWaresCategory> swcinfo = bll.GetSWInfo(winfo.CID);
            //获取类别信息
            IList<WaresCategory> wcinfo = bll.GetWinfo();

            ViewBag.swcinfo = swcinfo;
            ViewBag.wcinfo = wcinfo;

            return View(winfo);
        }
        /// <summary>
        /// 修改商品信息
        /// </summary>
        /// <param name="FormValues"></param>
        /// <param name="Url"></param>
        /// <returns></returns>
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult UpdateWares(FormCollection FormValues, HttpPostedFileBase Url, HttpPostedFileBase bookLocation)
        {
            //接收在线编辑器数据
            string EditorContents = FormValues["Contents"] ?? string.Empty;

            string FullFileUrl = "";
            string FullFileBook = "";
            //接收自己单独要上传的图片            
            if (Url != null)
            {
                string RndFileName = string.Format("{0}{1}{2}", DateTime.Now.ToString("yyMMdd"), Path.GetRandomFileName().Replace(".", string.Empty), Path.GetExtension(Url.FileName));
                FullFileUrl = string.Format("/upload/{0}", RndFileName);
                string SaveFilePathName = Server.MapPath(FullFileUrl);
                if (!YuHou.ReUse.ImageOperation.IntelligentSaveImageFile(Url.InputStream, SaveFilePathName, 0, true, "", new System.Drawing.Size(500, 500)))
                    Url.SaveAs(SaveFilePathName);

                //EditorContents += "上传图片成功！"; //上传成功提示，不需要可以删除。
            }
            else
            {
                //如过没有上传新图片就好用旧的
                FullFileUrl = FormValues["OldUrl"];
            }

            if (bookLocation != null)
            {
                string RndFileName = string.Format("{0}{1}{2}", DateTime.Now.ToString("yyMMdd"), Path.GetRandomFileName().Replace(".", string.Empty), Path.GetExtension(bookLocation.FileName));
                FullFileBook = string.Format("/Books/{0}", RndFileName);
                string SaveFilePathName = Server.MapPath(FullFileBook);

                bookLocation.SaveAs(SaveFilePathName);

                EditorContents += "上传电子书成功！"; //上传成功提示，不需要可以删除。
            }
            else
            {
                //如过没有上传新图片就好用旧的
                FullFileBook = FormValues["OldBook"];
            }
            int WID = Convert.ToInt32(FormValues["WID"]);
            string WName = FormValues["WName"];
            int CID = Convert.ToInt32(FormValues["CID"]);
            int SCID = Convert.ToInt32(FormValues["SCID"]);
            double OPrice = Convert.ToDouble(FormValues["OPrice"]);
            double PPrice = Convert.ToDouble(FormValues["PPrice"]);
            int Stock = Convert.ToInt32(FormValues["Stock"]);
            string Describe = FormValues["Describe"];

            Models.Wares winfo = new Models.Wares();
            winfo.WID = WID;
            winfo.WName = WName;
            winfo.CID = CID;
            winfo.SCID = SCID;
            winfo.OPrice = OPrice;
            winfo.PPrice = PPrice;
            winfo.Stock = Stock;
            winfo.Describe = Describe;
            winfo.Url = FullFileUrl;
            winfo.Introduce = EditorContents;
            winfo.bookLocation = FullFileBook;
            if (bll.UpdateWares(winfo) == 0)
            {
                var scripts = ("<script>alert('添加失败,请联系管理员');document.location.href = 'Wares-1'; </script>");
                return Content(scripts);
            }
            var script = ("<script>alert('修改成功');document.location.href = 'Wares'; </script>");
            return Content(script);
        }
        /// <summary>
        /// 置顶商品
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult OrderTimeWares()
        {
            int WID = Convert.ToInt32(Request.Form["WID"]);
            if (bll.OrderTimeWares(WID) == 0)
            {
                return Content("NO");
            }
            return Content("OK");
        }
        /// <summary>
        /// 删除商品
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DelWares()
        {
            int WID = Convert.ToInt32(Request.Form["WID"]);
            if (bll.DelWares(WID) == 0)
            {
                return Content("NO");
            }
            return Content("OK");
        }
        /// <summary>
        /// 商品搜索
        /// </summary>
        /// <returns></returns>
        [ValidateInput(false)]
        public ActionResult _WaresSearch()
        {
            //商品类别
            int CID;
            int.TryParse(Request.Form["CID"], out CID);
            //商品子类别
            int SCID;
            int.TryParse(Request.Form["SCID"], out SCID);
            //商品名
            string WName = Request.Form["WName"];
            //每页多少行
            int PageNum = 10;
            //第几页
            int Page;
            int.TryParse(Request.Form["Page"], out Page);
            Page = Page <= 0 ? 1 : Page;
            //商品状态
            int Status;
            int.TryParse(Request.Form["Status"], out Status);
            Page<AnyWares> winfo = bll
                .GetSerchWaresInfo(Page, PageNum, 
                CID, SCID, WName, Status);
            return View(winfo);
        }
        /// <summary>
        /// 上架
        /// </summary>
        /// <returns></returns>
        public ActionResult UpFrame()
        {
            int WID = Convert.ToInt32(Request.Form["WID"]);
            if (bll.UDFrame(0,WID) == 0)
            {
                return Content("NO");
            }
            return Content("OK");
        }
        /// <summary>
        /// 下架
        /// </summary>
        /// <returns></returns>
        public ActionResult DownFrame()
        {
            int WID = Convert.ToInt32(Request.Form["WID"]);
            if (bll.UDFrame(1, WID) == 0)
            {
                return Content("NO");
            }
            return Content("OK");
        }
        #endregion

        public ActionResult WaresSale()
        {
            IList<WaresCategory> wcinfo = bll.GetWinfo();
            ViewBag.wcinfo = wcinfo;
            return View();
        }

        public string GetWaresSale(int page=0,int limit=0,string value = "")
        {
            //分页获取销量
            WaresSaleModel waresSaleModel = new WaresSaleModel();
            List<WaresSale> waresList = bll.GetWaresSale(value,page,limit);
            waresSaleModel.code = 0;
            waresSaleModel.count = bll.GetCount();
            waresSaleModel.data = waresList;
            waresSaleModel.msg = "success";
            var jsonResult = JsonConvert.SerializeObject(waresSaleModel);
            return jsonResult;
        }
    }
}